package dxn.nl.file.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dxn.nl.file.biz.ConsumerStatusEnum;
import dxn.nl.file.biz.dao.ConsumerInfoDao;
import dxn.nl.file.biz.po.ConsumerInfoPo;
import dxn.nl.file.biz.service.ConsumerBaseService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ConsumerBaseServiceImpl extends ServiceImpl<ConsumerInfoDao, ConsumerInfoPo> implements ConsumerBaseService {
    @Override
    public boolean lockId(long id,int typeCode, String consumerThread) {
        LambdaQueryWrapper<ConsumerInfoPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ConsumerInfoPo::getId, id);
        lambdaQueryWrapper.eq(ConsumerInfoPo::getTypeCode, typeCode);

        ConsumerInfoPo infoPo = new ConsumerInfoPo();

        int dealResult = 0;
        ConsumerInfoPo existOne = this.baseMapper.selectOne(lambdaQueryWrapper);
        if(existOne != null)
        {
            if(existOne.getConsumerStatus() != null && ConsumerStatusEnum.start_deal.code==existOne.getConsumerStatus())
            {
                if(ConsumerStatusEnum.start_deal.code==existOne.getConsumerStatus()
                        || ConsumerStatusEnum.success.code==existOne.getConsumerStatus())
                {
                    return false;
                }
            }
            dealResult = this.baseMapper.lockId(existOne.getId(),existOne.getTypeCode(),existOne.getVersionNo(),consumerThread);
        }
        else {
            infoPo.setId(id);
            infoPo.setTypeCode(typeCode);
            infoPo.setVersionNo(1L);
            infoPo.setConsumerCount(0);
            infoPo.setConsumerStatus(1);
            infoPo.setStartTime(LocalDateTime.now());
            infoPo.setConsumerRefreshTime(LocalDateTime.now());
            infoPo.setConsumerThread(consumerThread);
            dealResult = this.baseMapper.insert(infoPo);
        }

        if(dealResult >0)
        {
            return true;
        }
        return false;
    }

    @Override
    public boolean unlockId(long id,int typeCode, int consumerStatus, String consumerThread) {
        int dealResult = this.baseMapper.unlockId(id,typeCode,consumerStatus,consumerThread);
        if(dealResult>0)
        {
            return true;
        }
        return false;
    }

    @Override
    public int removeDeadlockId() {
        return this.baseMapper.removeDeadlockId();
    }

    @Override
    public boolean refreshLockId(long id,int typeCode, String consumerThread) {
        int dealResult = this.baseMapper.refreshLockId(id,typeCode,consumerThread);
        if(dealResult>0)
        {
            return true;
        }
        return false;
    }
}
